package com.xuetang9.fujian.net;

import com.xuetang9.fujian.mychat.entity.BizType;
import com.xuetang9.fujian.mychat.util.SysDTO;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

/**
 * @author: fujian
 * @description: 客户端
 * @date: 2021/5/11 8:59
 * @version: V1.0
 * @package: com.xuetang9.fujian.net
 **/
public class ClientV1 {
    private String host;
    private int port;
    private Socket socket;
    private ObjectOutputStream outputStream;
    private ObjectInputStream inputStream;

    public ClientV1(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void init() throws IOException {
        socket = new Socket(host,port);
        outputStream = new ObjectOutputStream(socket.getOutputStream());
        inputStream = new ObjectInputStream(socket.getInputStream());
    }

    public void sendDTO(SysDTO dto) throws IOException {
        if (null == socket || null == inputStream || null == outputStream){
            init();
        }
        outputStream.writeObject(dto);
        outputStream.flush();
    }
    /*
     * @Description: 接收服务端传来的DTO对象
     * @param:
     * @return com.xuetang9.fujian.mychat.util.SysDTO
     * @author: fujian
     * @date 2021/5/11 9:06
    */
    public SysDTO readDto() throws IOException, ClassNotFoundException {
        Object dto = inputStream.readObject();
        if (dto instanceof SysDTO){
            return (SysDTO) dto;
        }
        return new SysDTO(BizType.未知业务类型);
    }

    /*
     * @Description: 适用于普通的业务对象 不适合私聊群聊 比如登录功能、注册功能
     * @param: dto
     * @return com.xuetang9.fujian.mychat.util.SysDTO
     * @author: fujian
     * @date 2021/5/11 9:07
    */
    public SysDTO sendAndReceive(SysDTO dto) throws IOException, ClassNotFoundException {
        sendDTO(dto);
        return readDto();
    }

    public void close(String nickName){
        SysDTO dto = new SysDTO(BizType.退出);
        dto.setNickName(nickName);
        try {
            sendDTO(dto);
            TimeUnit.MILLISECONDS.sleep(5000);
            // 关闭流 手动关闭资源
            inputStream.close();
            outputStream.close();
            socket.close();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

}
